package com.example.security;

import com.example.service.IRoleService;
import com.example.service.IUserService;
import com.example.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    IRoleService roleService;

    @Autowired
    IUserService userService;
    @Autowired
    RedisUtil redisUtil;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //从数据库中取出该用户
        MyUserDetails userDetails = null;
        userDetails = userService.getUserDetailsByUserName(userName);

        //用户不存在则抛出异常
        if (userDetails == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        //将用户角色信息添加到UserDetails权限集
        userDetails.setAuthorities(getUserAuthority(userName));
        return userDetails;
    }

    public List<GrantedAuthority> getUserAuthority(String userName) {
        // 通过内置的工具类，把权限字符串封装成GrantedAuthority列表
        return AuthorityUtils.commaSeparatedStringToAuthorityList(userService.getUserAuthorityInfo(userName));
    }
}
